﻿using Cofe.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.IO;
#if NETFX_CORE
using Windows.Storage;
using Windows.Storage.Streams;
using Cofe.Core.Implements;
#endif

namespace Cofe.Core.Session
{
#if NETFX_CORE
    public class WinRT_SuspensionManager : ISuspensionManager
    {
        public WinRT_SuspensionManager()
        {

        }

        public WinRT_SuspensionManager(string filename)
        {
            _filename = filename;
        }

        private Dictionary<string, object> sessionState_ = new Dictionary<string, object>();
        private List<Type> knownTypes_ = new List<Type>();
        private string _filename = "_cofe.xml";

        public Dictionary<string, object> SessionState
        {
            get { return sessionState_; }
        }

        public List<Type> KnownTypes
        {
            get { return knownTypes_; }
            set { knownTypes_ = value; }
        }

        async public Task SaveAsync()
        {
            // Get the output stream for the SessionState file.
            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(_filename, CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream raStream = await file.OpenAsync(FileAccessMode.ReadWrite))
            {
                using (IOutputStream outStream = raStream.GetOutputStreamAt(0))
                {
                    // Serialize the Session State.
                    DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
                    serializer.WriteObject(outStream.AsStreamForWrite(), sessionState_);
                    await outStream.FlushAsync();
                }
            }
        }

        // Restore the saved sesison state
        async public Task RestoreAsync()
        {
            // Get the input stream for the SessionState file.
            try
            {
                StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(_filename);
                if (file == null) return;
                IInputStream inStream = await file.OpenSequentialReadAsync();

                // Deserialize the Session State.
                DataContractSerializer serializer = new DataContractSerializer(typeof(Dictionary<string, object>), knownTypes_);
                sessionState_ = (Dictionary<string, object>)serializer.ReadObject(inStream.AsStreamForRead());
            }
            catch (Exception ex)
            {
                // Restoring state is best-effort.  If it fails, the app will just come up with a new session.
            }
        }
    }
#endif
}
